/*!
 * Cookie module v1.0.0 of jRaiser javascript library
 * http://code.google.com/p/jraiser/
 *
 * Author: Heero.Luo
 * Licensed under MIT license
 *
 * Date: Tue Jun 05 2012 10:33:00 GMT+0800
 */
define(function(require, exports, module) { 'use strict';

var core = require('core/1.0.x/core');


// 时间单位
var timeUnits = {
	SEC : 1000, MIN : 60 * 1000, HOUR : 60 * 60 * 1000,
	DAY : 24 * 60 * 60 * 1000,
	MONTH : 30 * 24 * 60 * 60 * 1000,
	YEAR : 365 * 24 * 60 * 60 * 1000
};

// 匹配带单位的时间值
var rTime = /^(\d+(?:\.\d+)?)\s*([a-z]+?)s?$/i;

// 转换为时间数字
function toTimeSpan(val) {
	if ( rTime.test(val) ) {
		var unit = RegExp.$2.toUpperCase();
		// 无此时间单位，抛出异常
		if ( !timeUnits.hasOwnProperty(unit) ) {
			throw new Error('not such time unit(' + RegExp.$2 + ')');
		}

		return parseFloat(RegExp.$1) * timeUnits[unit];
	}
	
	return parseFloat(val) || 0;
}


core.extend(exports, {
	/**
	 * 写入cookie
	 * @param {String} cookie名
	 * @param {String} cookie值
	 * @param {Object} 设置
	 *   domain {String} 域
	 *   path {String} 路径
	 *   expires {Date|Number|String} 过期时间
	 *   secure {Boolean} 是否只在https连接中有效
	 *   encode {Function} cookie编码函数，默认为encodeURIComponent
	 */
	set : function (name, value, o) {
		o = core.extend({
			encode : encodeURIComponent
		}, o);
			
		var expires = o.expires, text = o.encode(name) + '=' + o.encode(value);
		
		if (typeof expires === 'string') { expires = toTimeSpan(expires); }
		if (typeof expires === 'number') {
			var d = new Date();
			d.setTime(d.getTime() + expires);
			expires = d;
		}
		if ( core.isDate(expires) ) { text += '; expires=' + expires.toUTCString(); }

		if (o.path) { text += '; path=' + o.path; }
		if (o.domain) { text += '; domain=' + o.domain; }
		if (o.secure === true) { text += '; secure'; }
		
		document.cookie = text;
	},
	
	/**
	 * 读取cookie
	 * @param {String} cookie名
	 * @param {Object} 选项
	 *   encode {Function} cookie编码函数，默认为encodeURIComponent
	 *   decode {Function} cookie解码函数，默认为decodeURIComponent
	 * @return {String} cookie值
	 */
	get : function(name, o) {
		o = core.extend({
			encode : encodeURIComponent,
			decode : decodeURIComponent
		}, o);

		name = '; ' + o.encode(name) + '=';
		var cookie = '; ' + document.cookie, beginPos = cookie.indexOf(name), endPos;
		
		if (beginPos === -1) { return null; }

		beginPos += name.length;
		endPos = cookie.indexOf(';', beginPos);
		if (endPos === -1) { endPos = cookie.length; }

		return o.decode( cookie.substring(beginPos, endPos) );
	},
	
	/**
	 * 移除cookie
	 * @param {String} cookie名
	 * @param {Object} 选项
	 *   domain {String} 域
	 *   path {String} 路径
	 *   secure {Boolean} 是否只在安全连接中有效
	 *   encode {Function} cookie编码函数，默认为encodeURIComponent
	 */
	remove : function (name, o) {
		o = o || { };
		o.expires = new Date(0);
		
		this.set(name, '', o);
	}
});

});